package com.sc.app.security.openidauth;

import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.SocialUserDetailsService;

import java.util.HashSet;
import java.util.Set;

/**
 * @author sc
 * Created on  2018/1/24
 */
@Data
public class OpenIdAuthProvider implements AuthenticationProvider {

    private SocialUserDetailsService userDetailsService;
    private UsersConnectionRepository usersConnectionRepository;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        OpenIdAuthToken authToken = (OpenIdAuthToken) authentication;
        Set<String> providerUserIds = new HashSet<>();
        providerUserIds.add((String) authentication.getPrincipal());
        Set<String> userIds = usersConnectionRepository.findUserIdsConnectedTo(authToken.getProviderId(),providerUserIds);
        if(CollectionUtils.isEmpty(userIds)||userIds.size()!=1){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        String userId = userIds.iterator().next();
        UserDetails userDetails = userDetailsService.loadUserByUserId(userId);
        if(userDetails==null){
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }
        OpenIdAuthToken authToken1 = new OpenIdAuthToken(userDetails,userDetails.getAuthorities());
        authToken1.setDetails(authToken.getDetails());
        return authToken1;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return OpenIdAuthToken.class.isAssignableFrom(aClass);
    }
}
